object FunctionVsMethodDemo extends App {
  // 定义学生类
  case class Student(id: String, name: String, var className: String, scores: Map[String, Int])

  // 学生数据源
  val students = scala.collection.mutable.ListBuffer[Student](
    Student("S2025001", "张三", "高一(1)班", Map("数学" -> 85, "语文" -> 90)),
    Student("S2025002", "李四", "高一(1)班", Map("数学" -> 92, "语文" -> 88)),
    Student("S2025003", "王五", "高一(2)班", Map("数学" -> 76, "语文" -> 82))
  )

  // 1. 类中的方法（Method）
  class StudentManager {
    // 方法：根据ID查询学生
    def findStudentById(studentId: String): Option[Student] = {
      students.find(_.id == studentId)
    }

    // 方法：更新学生班级
    def updateStudentClass(studentId: String, newClass: String): Boolean = {
      findStudentById(studentId) match {
        case Some(student) =>
          student.className = newClass
          true
        case None =>
          false
      }
    }
  }

  // 2. 独立函数（Function）
  // 函数：计算学生平均分
  val calculateStudentAverage: Student => Double = (student) => {
    if (student.scores.isEmpty) 0.0
    else student.scores.values.sum.toDouble / student.scores.size
  }

  // 函数：获取学生等级
  val getStudentGrade: Student => String = (student) => {
    val avg = calculateStudentAverage(student)
    if (avg >= 90) "优秀"
    else if (avg >= 80) "良好"
    else if (avg >= 70) "中等"
    else if (avg >= 60) "及格"
    else "不及格"
  }

  // 3. 方法与函数的使用
  val manager = new StudentManager()

  // 使用方法
  val student = manager.findStudentById("S2025002")
  student match {
    case Some(s) => println(s"找到学生：${s.name}，班级：${s.className}")
    case None => println("未找到学生")
  }

  // 调用更新方法
  val updateSuccess = manager.updateStudentClass("S2025002", "高一(3)班")
  println(s"更新班级成功：$updateSuccess")
  manager.findStudentById("S2025002").foreach(s =>
    println(s"更新后班级：${s.className}")
  )

  // 使用函数
  students.foreach { s =>
    val avg = calculateStudentAverage(s)
    val grade = getStudentGrade(s)
    println(f"${s.name} 的平均分：${avg}%.1f，等级：$grade")
  }

  // 4. 方法转换为函数（使用下划线）
  val findFunc = manager.findStudentById _
  val result = findFunc("S2025001")
  println(s"\n通过函数查找：${result.map(_.name)}")
}